package com.geekyang.rabbitmqapi.returnlistener;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ccyang
 * @date 2018/10/14 13:19
 * Return 消息机制
 */
public class Producer {

    public static void main(String[] args) throws IOException, TimeoutException {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        String exchangeName = "test_return_exchange";
        String routingKey = "return.save";
        String routingKeyError = "abc.save";

        channel.addReturnListener(new ReturnListener() {
            /**
             *
             * @param i 响应码
             * @param s 响应文本
             * @param s1 路由的交换机
             * @param s2 路由的key
             * @param basicProperties
             * @param bytes 消息体内容
             * @throws IOException
             */
            @Override
            public void handleReturn(int i, String s, String s1, String s2,
                                     AMQP.BasicProperties basicProperties, byte[] bytes) throws IOException {
                System.err.println("---------handler return--------");
                System.err.println("replyCode: " + i);
                System.err.println("replyText: " + s);
                System.err.println("exchange: " + s1);
                System.err.println("queue: " + s2);
                System.err.println("basicProperties: " + basicProperties);
                System.err.println("body: " + new String(bytes));
            }
        });

        String msg = "Hello RabbitMQ return message";

        // 第三个参数决定是否启用 Return Listener
//      channel.basicPublish(exchangeName, routingKey, true, null, msg.getBytes());

        channel.basicPublish(exchangeName, routingKeyError, true, null, msg.getBytes());



    }
}
